//
//  MobilePhoneController.m
//  wanzhaoIM
//
//  Created by wanzhao on 16/1/6.
//  Copyright © 2016年 liuyuantao. All rights reserved.
//

#import "MobilePhoneController.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "CXmppMgr.h"
#import "CGroupMemberModel.h"
#import "CGroupMemberMgr.h"
#import "CContactMgr.h"
#import "MBProgressHUD+WZ.h"
#import "CXmppRequestMgr.h"
#import "CContactModel.h"
#import <MessageUI/MessageUI.h>
#import "MobilePhoneCell.h"
#import "UIUtil.h"
#import "UIBarButtonItem+category.h"

@interface MobilePhoneController ()<UITableViewDataSource, UITableViewDelegate, MFMessageComposeViewControllerDelegate>

@property (nonatomic, strong) NSMutableArray *memeberArray;

@property (nonatomic, strong) NSMutableArray *messageArray;

@property (nonatomic, strong) CGroupMemberMgr *groupMemMgr;

@property (nonatomic, strong) CContactMgr *conMgr;

@property (nonatomic, strong) CGroupMgr *groupMgr;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, weak) UILabel *label;

@end

@implementation MobilePhoneController

- (NSMutableArray *)memeberArray
{
    if (_memeberArray == nil) {
        _memeberArray = [NSMutableArray array];
    }
    return _memeberArray;
}

- (NSMutableArray *)messageArray
{
    if (_messageArray == nil) {
        _messageArray = [NSMutableArray array];
    }
    return _messageArray;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPGETGROUPMEMBERS object:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"未绑定详情"];
    

    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"确定" target:self sel:@selector(ensureSendMessage) titleFont:Font18 titleColor:WhiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetGroupMembers:) name:K_XMPPGETGROUPMEMBERS object:nil];
    
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = UITextAlignmentCenter;
    label.numberOfLines = 0;
    label.text = @"没有未绑定手机号的联系人，点击确定，您就可以向所有的群成员发送短信啦！";
    label.frame = CGRectMake(15.0f, 0, HARDWARE_SCREEN_WIDTH - 30.0f, HARDWARE_SCREEN_HEIGHT-64);
    [self.view addSubview:label];
    label.hidden = YES;
    self.label = label;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.frame = self.view.bounds;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //bug 9539 fixed by lixu 不让用户点击
    _tableView.userInteractionEnabled = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundColor = ClearColor;
    _tableView.hidden = YES;

    
    self.groupMemMgr = [[CGroupMemberMgr alloc] init];
    self.conMgr = [[CContactMgr alloc] init];
    self.groupMgr = [[CGroupMgr alloc] init];
    
    if ([CXmppMgr shareInstance].reachability.currentReachabilityStatus != NotReachable) {
        if (self.group) {
            CContactModel *current = [self.conMgr loadCurContact];
            NSArray *array = [self.groupMemMgr loadAllGroupMemberByGroupID:self.group.GroupId];
            if (array.count == self.group.UserNum) {
                [self.memeberArray removeAllObjects];
                [self.messageArray removeAllObjects];
                for (CGroupMemberModel *groupModel in array) {
                    CContactModel *contact = [self.conMgr loadNotDelContactWithUserId:groupModel.UserId];
                    if (M_ISSTRNULL(contact.MobileTelephone)) {
                        if (![contact.UserID isEqualToString:current.UserID]) {
                            [self.memeberArray addObject:contact];
                        }

                    } else {
                        [self.messageArray addObject:contact.MobileTelephone];
                    }
                }
                if (self.memeberArray.count > 0) {
                    [_tableView reloadData];
                    label.hidden = YES;
                    _tableView.hidden = NO;
                } else {
                    label.hidden = NO;
                    _tableView.hidden = YES;
                }
            } else {
                
                [[CXmppRequestMgr shareInstance] getGroupMembersWithGroup:self.group];
                [UIUtil addMBProgressViewTitle:@"加载中..." inView:self.view alpha:1.0 failureTitle:@"加载失败"];
            }
            
        }
    } else {
        [MBProgressHUD showError:@"加载失败"];
    }
    
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
}



- (void)didGetGroupMembers:(NSNotification *)notice
{
    [UIUtil hideMBProgressViewForView:self.view];
    
    NSArray *array = [self.groupMemMgr loadAllGroupMemberByGroupID:self.group.GroupId];
    
    if (array.count > 0) {
        CContactModel *current = [self.conMgr loadCurContact];
        [self.memeberArray removeAllObjects];
        [self.messageArray removeAllObjects];
        for (CGroupMemberModel *groupModel in array) {
            CContactModel *contact = [self.conMgr loadNotDelContactWithUserId:groupModel.UserId];
            if (contact) {
                if (M_ISSTRNULL(contact.MobileTelephone)) {
                    if (![contact.UserID isEqualToString:current.UserID]) {
                        [self.memeberArray addObject:contact];
                    }
                } else {
                    [self.messageArray addObject:contact.MobileTelephone];
                }
 
            }
        }
        if (self.memeberArray.count > 0) {
            [_tableView reloadData];
            self.label.hidden = YES;
            _tableView.hidden = NO;
        } else {
            self.label.hidden = NO;
            _tableView.hidden = YES;
        }
    }

}

- (void)ensureSendMessage
{
    CContactModel *current = [self.conMgr loadCurContact];

    // 判断用户设备能否发送短信
    if (![MFMessageComposeViewController canSendText]) {
        return;
    }
    
    if (self.messageArray.count <= 0) {
        return;
    }
    for (NSString *num in self.messageArray) {
        if ([num isEqualToString:current.MobileTelephone]) {
            [self.messageArray removeObject:num];
            break;
        }
    }
    // 1. 实例化一个控制器
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    // 2. 设置短信内容
    // 1) 收件人
    controller.recipients = self.messageArray;
    
    // 2) 短信内容
    //            controller.body = @"给您拜个晚年，祝您晚年快乐！";
    
    // 3) 设置代理
    controller.messageComposeDelegate = self;
    
    // 3. 显示短信控制器
    [self presentViewController:controller animated:YES completion:nil];
    

}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.memeberArray.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];
    label.font = Font14;
    label.text = [NSString stringWithFormat:@"有%zd位联系人未绑定手机，将无法接收短信",self.memeberArray.count];
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *DepartMemberCellIdentifier = @"MobilePhoneCell";
    UITableViewCell *cell = nil;
    MobilePhoneCell *departMemberCell = [tableView dequeueReusableCellWithIdentifier:DepartMemberCellIdentifier];
    if (departMemberCell == nil) {
        departMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"MobilePhoneCell" owner:self options:nil] objectAtIndex:0];
    }
    CContactModel *contactModel = self.memeberArray[indexPath.row];
    departMemberCell.icon.layer.cornerRadius = 3.0f;
    departMemberCell.icon.layer.masksToBounds = YES;
    
    [departMemberCell.nameLabel setText:contactModel.UserName];
    
    [departMemberCell.positionLabel setText:contactModel.Position];
    [departMemberCell.seperatorLine setHidden:NO];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell = departMemberCell;
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
